package com.shinowit.service;

import java.sql.Types;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shinowit.dao.mapper.SysUserMapper;
import com.shinowit.model.SysUser;

@Service
public class UserService {

	@Resource
	private JdbcTemplate jt;
	
	@Resource
	private SysUserMapper sys_user_dao;
	
	@Transactional
	public boolean createUser(SysUser user){
		boolean result=false;
		try{
			sys_user_dao.insert(user);
			//写角色信息
			for (String s:user.getRoles()){
				jt.update("insert into sys_user_role(sys_role_code,user_code) values(?,?)", new Object[]{s,user.getUserCode()},new int[]{Types.VARCHAR,Types.VARCHAR});
			}
			result=true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	
	@Transactional
	public boolean editUser(SysUser user){
		boolean result=false;
		try{
			sys_user_dao.updateByPrimaryKey(user);
			jt.update("delete from sys_user_role where user_code=? ",new Object[]{user.getUserCode()},new int[]{Types.VARCHAR});
			//写角色信息
			for (String s:user.getRoles()){
				jt.update("insert into sys_user_role(sys_role_code,user_code) values(?,?)", new Object[]{s,user.getUserCode()},new int[]{Types.VARCHAR,Types.VARCHAR});
			}
			result=true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	
	@Transactional
	public boolean deleteUser(SysUser user){
		boolean result=false;
		try{
			jt.update("delete from  sys_user_role where user_code=?", new Object[]{user.getUserCode()},new int[]{Types.VARCHAR});
			sys_user_dao.deleteByPrimaryKey(user.getUserCode());
			result=true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}	
	
}
